from lib import helper, resp
from lib.snowflake import Snowflake
from models.user_chapter import UserChapter


class ChapterService:

    def chapter_list(self, title: str = ""):
        c = UserChapter.table()
        if title != "":
            c.where("Title", "like", f"%{title}%")
        c.where("IsValid", 1)

    def chapter_save(self, novel_id=0, data: dict = {}):
        t = UserChapter.table()
        info = t.where("ChapterId", novel_id).first()
        if info:
            rs = t.update(helper.update_data_time(data))
        else:
            data["ChapterId"] = Snowflake.unique_id()
            rs = UserChapter.table().insert(helper.add_data_time(data))
        if not rs:
            return resp.ret_failed()
        return resp.ret_obj()

    def chapter_delete(self, novel_id):
        rs = UserChapter.table().where("ChapterId", novel_id).update({"IsValid": 0})
        if rs:
            return resp.ret_obj()
        return resp.ret_failed()
